package com.cicadamob.contact.api.Utils.NetWork;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.http.entity.StringEntity;

import android.content.Context;

import com.cicadamob.contact.api.Utils.Logger.AppLogger;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * Http操作类
 * 
 * @author mengxs
 * 
 */

public class HttpUtil {
	public enum RequestMethod {
		GET, POST
	};
    public static final String  charset="utf-8";
	/** XML请求 map key **/
	public static final String XML = "xml";
	public static final String JSON = "json";

	/**
	 * http请求 post get (此方法已经异步)
	 * 
	 * @param <T>
	 * @param requtestMethod
	 *            //RequestMethod.POST or RequestMethod.GET
	 * @param url
	 *            网络地址
	 * @param requestMap
	 *            请求参数map 如果是纯xml请求 map.put(HttpUtil.XML,"相应xml内容");
	 * @param callback
	 *            回调方法
	 */
	public static <T> void HttpRequest(Context context,
			RequestMethod requtestMethod, String url,Map<String, String> requestMap, HttpRequestCallBack<T> callback) {
		if (!NetWorkUtil.isConnected(context)) {
			return;
		}
		boolean isResponseGzip=false;
		HttpMethod method = null;
		switch (requtestMethod) {
		case GET:
			method = HttpMethod.GET;
			doGetRequest(method, url, requestMap, callback,isResponseGzip);
			break;
		case POST:
			method = HttpMethod.POST;
			doPostRequst(method, url, requestMap, callback,isResponseGzip);
			break;
		}

	}
	
	
	
	/**
	 * http请求 post get (此方法已经异步)
	 * 
	 * @param <T>
	 * @param requtestMethod
	 *            //RequestMethod.POST or RequestMethod.GET
	 * @param url
	 *            网络地址
	 * @param isResponseGzip
	 *           返回结果是否是压缩流
	 * @param requestMap
	 *            请求参数map 如果是纯xml请求 map.put(HttpUtil.XML,"相应xml内容");
	 *            
	 *                     如果是纯json请求map.put(HttpUtil.JSON,"相应JSON字符串");
	 * @param callback
	 *            回调方法
	 */
	public static <T> void HttpRequest(Context context,
			RequestMethod requtestMethod, String url,boolean isResponseGzip,
			Map<String, String> requestMap, HttpRequestCallBack<T> callback) {
		if (!NetWorkUtil.isConnected(context)) {
			return;
		}
		HttpMethod method = null;
		switch (requtestMethod) {
		case GET:
			method = HttpMethod.GET;
			doGetRequest(method, url, requestMap, callback,isResponseGzip);
			break;
		case POST:
			method = HttpMethod.POST;
			doPostRequst(method, url, requestMap, callback,isResponseGzip);
			break;
		}

	}
	
	
	/**
	 * 下载文件 支持断点续传  (此方法已经异步)
	 * 
	 * @param url
	 *            网络地址
	 * @param target
	 *            存储路径
	 * @param autoResume
	 *            // true 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
	 * @param autoRename
	 *            // true 如果从请求返回信息中获取到文件名，下载完成后自动重命名.
	 * @param callback
	 * @return HttpHandler // handler.cancel(mayInterruptIfRunning)  调用cancel()方法停止下载;
	 */
	@SuppressWarnings("rawtypes")
	public static HttpHandler doDownloadFile(Context context, String url,
			String target, boolean autoResume, boolean autoRename,
			final HttpRequestCallBack<File> callback) {
		if (!NetWorkUtil.isConnected(context)) {
			return null;
		}
		HttpUtils http = new HttpUtils();
		HttpHandler handler = http.download(url, target, autoResume,
				autoRename, new RequestCallBack<File>() {

					@Override
					public void onSuccess(ResponseInfo<File> responseInfo) {
						// TODO Auto-generated method stub
						callback.onSuccess(responseInfo);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
						callback.onFailure(error, msg);
					}

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						// TODO Auto-generated method stub
						super.onLoading(total, current, isUploading);
						callback.onLoading(total, current, isUploading);
					}

					@Override
					public void onStart() {
						// TODO Auto-generated method stub
						super.onStart();
						callback.onStart();
					}

					@Override
					public void onStopped() {
						// TODO Auto-generated method stub
						super.onStopped();
						callback.onStopped();
					}

				});
		// handler.cancel(mayInterruptIfRunning); //调用cancel()方法停止下载
		return handler;

	}
	

	/**
	 * get请求
	 * 
	 * @param requtestMethod
	 * @param url
	 * @param requestMap
	 * @param callback
	 */
	private static <T> void doGetRequest(HttpMethod requtestMethod, String url,
			Map<String, String> requestMap,
			final HttpRequestCallBack<T> callback,boolean isResponseGzip) {
		StringBuilder urlBuilder = new StringBuilder(url);
		if (requestMap != null && requestMap.size() > 0) {
			urlBuilder.append("?");
			for (String key : requestMap.keySet()) {
				urlBuilder.append(key).append("=").append(requestMap.get(key))
						.append("&");
			}
			urlBuilder.deleteCharAt(urlBuilder.length() - 1);
		}
		doXUtilsHttpRequest(requtestMethod, url, new RequestParams(), callback,isResponseGzip);
	}

	/**
	 * post请求
	 * 
	 * @param requtestMethod
	 * @param url
	 * @param requestMap
	 * @param callback
	 */
	private static <T> void doPostRequst(HttpMethod requtestMethod, String url,
			Map<String, String> requestMap, HttpRequestCallBack<T> callback,boolean isResponseGzip) {
		RequestParams params = new RequestParams();
		if (requestMap != null && requestMap.size() == 1
				&& requestMap.containsKey(XML)) {
			try {
				params.setBodyEntity(new StringEntity(requestMap.get(XML),
						charset));
			AppLogger.d("http", "request url="+url +"\r\n"+requestMap.get(XML));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(requestMap != null && requestMap.size() == 1
				&& requestMap.containsKey(JSON)){
		
			try {
				params.setBodyEntity(new StringEntity(requestMap.get(JSON),
						charset));
				AppLogger.d("http", "request url="+url +"\r\n"+requestMap.get(JSON));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else if (requestMap != null && requestMap.size() > 0) {
	/*		for (String key : requestMap.keySet()) {
				 
				params.addQueryStringParameter(key, requestMap.get(key));
			}*/
		/*	JSONObject requestJson=new JSONObject(requestMap);
			try {
				params.setBodyEntity(new StringEntity(requestJson.toString(),
						charset));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		}

		doXUtilsHttpRequest(requtestMethod, url, params, callback,isResponseGzip);

	}

	
	/**
	 * 调用xutil(普通post/get) Http请求
	 * 
	 * @param requtestMethod
	 * @param url
	 * @param requestMap
	 * @param callback
	 */
	private static <T> void doXUtilsHttpRequest(HttpMethod requtestMethod,
			final String url, RequestParams params,
			final HttpRequestCallBack<T> callback,boolean isResponseGzip) {
		HttpUtils http = new HttpUtils();
		http.send(requtestMethod, url, params, new RequestCallBack<T>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				callback.onFailure(arg0, arg1);
			}

			@Override
			public void onSuccess(ResponseInfo<T> arg0) {
				// TODO Auto-generated method stub
				callback.onSuccess(arg0);
				AppLogger.d("http", "response url="+url +"\r\n"+arg0.result);
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
				callback.onLoading(total, current, isUploading);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				callback.onStart();
			}

			@Override
			public void onStopped() {
				// TODO Auto-generated method stub
				super.onStopped();
				callback.onStopped();
			}
		},isResponseGzip);
	}

}
